package com.tao.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tao.dto.MessageDto;
import com.tao.entity.Message;
import com.tao.enums.MessageType;
import com.tao.service.MessageService;
import com.tao.vo.ResponseResult;
import com.tao.vo.SocketResult;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author  诸葛先生
 * 功能：聊天业务处理器
 */
@Component
public class ChatMessageHandler {
    private static MessageService messageService;

    @Autowired
    public void setMessageService(MessageService messageService) {
        ChatMessageHandler.messageService = messageService;
    }


    public static void execute(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        try {
            MessageDto messageDto = JSON.parseObject(msg.text(), MessageDto.class);
            Message message = JSON.parseObject(messageDto.getData().toString(),Message.class);
            switch (MessageType.match(message.getType())) {
                case PRIVATE:
                    Channel channel = IMSocketHandler.USERS.get(message.getToId());
                    Channel ctxChannel = ctx.channel();
                    //不管用户在不在线,将信息存储进数据库中
                    AttributeKey<Long> creatorId = AttributeKey.valueOf("userId");
                    Long id = ctxChannel.attr(creatorId).get();
                    message.setCreateBy(id);
                    System.out.println(message.toString());
                    messageService.addMessage(message);
                    if (channel != null) {
//                        channel.writeAndFlush(SocketResult.success(JSON.toJSONString(message)));
                        channel.writeAndFlush(ResponseResult.webSocketOkResult(message));
                    }
                    break;
                case GROUP:
                    messageService.addMessage(message);
                    IMSocketHandler.GROUP.writeAndFlush(SocketResult.success(
                            "群消息(" + message.getCreateBy() + ")", message.getContent()));
                    break;
                default:
                    ctx.channel().writeAndFlush(new TextWebSocketFrame(ResponseResult.errorResult(402,"不支持的消息类型").toString()));

            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
